package com.demo.myapplication.fragment;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;

import com.demo.myapplication.R;
import com.demo.myapplication.activity.MainActivity;
import com.demo.myapplication.utils.CommonUtils;

public class BrightnessFragment extends Fragment {

  private static String Tag = BrightnessFragment.class.getSimpleName();

  private TextView sysBrightness, userBrightness;
  private SeekBar brightSeek;
  private CheckBox brightCb;
  private NestedScrollView scrollView;
  private Button btnPopWindow, btnPopMenu, btnBottomSheet;

  public static BrightnessFragment newInstance(Bundle bundle) {
    BrightnessFragment fragment = new BrightnessFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  @Override
  public void onResume() {
    super.onResume();
    Log.d(Tag, "onResume,isChangeTheme=" + isChangeTheme);
    isChangeTheme = false;
    setShade();
    scrollView.post(new Runnable() {
      @Override
      public void run() {
        scrollView.scrollTo(0, scrollY);
      }
    });
  }

  @Override
  public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("scroll", scrollView.getScrollY());
    Log.d(Tag, "onSaveInstanceState,scroll=" + scrollView.getScrollY());
  }

  private int scrollY;

  @Override
  public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
    super.onViewStateRestored(savedInstanceState);
    if (savedInstanceState != null) {
      scrollY = savedInstanceState.getInt("scroll");
      scrollView.scrollTo(0, scrollY);
      Log.d(Tag, "onViewStateRestored,scroll=" + scrollY);
    }
  }

  private boolean isChangeTheme = false;

  @Override
  public void onPause() {
    super.onPause();
    Log.d(Tag, "onPause,isChangeTheme=" + isChangeTheme);
    if (isChangeTheme) {
      return;
    }
//    setShade(true);
    CommonUtils.removeShade(getActivity());
  }

  private void setShade() {
    //onResume depend on the night mode,if true,add ,else remove
    //onPause if true,remove ,else
    boolean isNight = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(CommonUtils.IS_NIGHT_MODE, false);
    if (isNight) {
      CommonUtils.addShade(getActivity());
    } else {
      CommonUtils.removeShade(getActivity());
    }
  }

  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_brightness, container, false);

    sysBrightness = (TextView) view.findViewById(R.id.system_brightness);
    userBrightness = (TextView) view.findViewById(R.id.user_brightness);

    brightSeek = (SeekBar) view.findViewById(R.id.brightness_seekbar);
    brightCb = (CheckBox) view.findViewById(R.id.brightness_checkbox);

    scrollView = (NestedScrollView) view.findViewById(R.id.scroll);
    Button refreshBtn = (Button) view.findViewById(R.id.refresh);
    btnPopMenu = (Button) view.findViewById(R.id.popup_menu);
    btnPopWindow = (Button) view.findViewById(R.id.popup_window);
    btnBottomSheet = (Button) view.findViewById(R.id.bottom_sheet);

    btnPopMenu.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        showPopMenu();
      }
    });

    btnPopWindow.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        showPopWindow();
      }
    });

    btnBottomSheet.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        showBottomSheet();
      }
    });

    refreshBtn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        initData();
        updateBrightness();
      }
    });
    //first get system brightness and set it to user
    initData();
    updateBrightness();

    FloatingActionButton fab = ((MainActivity) getActivity()).getFab();
    fab.show();
    if (PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(CommonUtils.IS_NIGHT_MODE, false)) {
      fab.setImageResource(R.drawable.ic_day);
      //add alpha
    } else {
      fab.setImageResource(R.drawable.ic_night);
    }
    fab.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        boolean isNight = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(CommonUtils.IS_NIGHT_MODE, false);
        isNight = !isNight;
        PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().putBoolean(CommonUtils.IS_NIGHT_MODE, isNight).commit();
//        CommonUtils.changeTheme(!isNight, getActivity());
        isChangeTheme = true;
        getActivity().recreate();
      }
    });

    brightCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().putBoolean(CommonUtils.USER_BRIGHTNESS_MODE, isChecked).commit();
        //update light from current seek progress
        initData();
        updateBrightness();
      }
    });

    brightSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
      @Override
      public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
          PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().putInt(CommonUtils.USER_BRIGHTNESS, seekBar.getProgress()).commit();
          if (brightCb.isChecked()) {
            brightCb.setChecked(false);
          }
          initData();
          updateBrightness();
        }
      }

      @Override
      public void onStartTrackingTouch(SeekBar seekBar) {

      }

      @Override
      public void onStopTrackingTouch(SeekBar seekBar) {
      }
    });

    //load system brightness and user brightness info
    //register change and set
    return view;
  }

  private BottomSheetDialog bottomDialog;
  private BottomSheetAdapter bottomAdapter;

  private void showBottomSheet() {

    if (bottomDialog == null) {
      initBottomSheet();
    }
    if (bottomDialog.isShowing()) {
      return;
    }
    bottomDialog.show();
  }

  private void initBottomSheet() {
    bottomDialog = new BottomSheetDialog(getContext());

    RecyclerView recyclerView = (RecyclerView) getActivity().getLayoutInflater().inflate(R.layout.recyclerview, null);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    bottomAdapter = new BottomSheetAdapter();
    recyclerView.setAdapter(bottomAdapter);

    bottomDialog.setContentView(recyclerView);
    bottomAdapter.setOnItemClickListener(new BottomSheetAdapter.OnItemClickListener() {
      @Override
      public void onItemClick(int position, String text) {
        Snackbar.make(btnBottomSheet, text, Snackbar.LENGTH_SHORT).show();
        bottomDialog.dismiss();
      }
    });
  }

  private PopupWindow popupWindow;
  private View windowView;

  private void showPopWindow() {
    if (popupWindow == null) {
      initPopWindow();
    }
    if (popupWindow.isShowing()) {
      return;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
      blur(snapShotWithoutStatusBar(getActivity()), windowView);
    } else {
      backgroundAlpha(0.3f);
//      popupWindow.setBackgroundDrawable(new ColorDrawable(Color.));
    }
    popupWindow.showAtLocation(btnPopWindow, Gravity.CENTER, 0, 0);
  }

  private void initPopWindow() {
    if (windowView != null) {
      return;
    }
    windowView = getActivity().getLayoutInflater().inflate(R.layout.pop_window, null);
    popupWindow = new PopupWindow(windowView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
    popupWindow.setTouchable(true);
    popupWindow.setOutsideTouchable(true);
    popupWindow.setBackgroundDrawable(new BitmapDrawable());
    windowView.findViewById(R.id.pop_close).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (popupWindow != null && popupWindow.isShowing()) {
          popupWindow.dismiss();
        }
      }
    });
    windowView.setOnTouchListener(new View.OnTouchListener() {
      @Override
      public boolean onTouch(View view, MotionEvent event) {
        if (popupWindow != null && popupWindow.isShowing()) {
          View v = windowView.findViewById(R.id.pop_layout);
          int height = v.getTop();
          int y = (int) event.getY();
          if (event.getAction() == MotionEvent.ACTION_UP) {
            if (y < height || y > v.getBottom()) {
              popupWindow.dismiss();
            }
          }
          // pop.dismiss();
        }
        return true;
      }
    });
    popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
      @Override
      public void onDismiss() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
//          blur(windowView.getDrawingCache(), windowView);
//        } else {
          backgroundAlpha(1);
        }
      }
    });
  }

  /**
   * 设置添加屏幕的背景透明度
   *
   * @param bgAlpha
   */
  public void backgroundAlpha(float bgAlpha) {
    WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
    lp.alpha = bgAlpha; //0.0-1.0
    getActivity().getWindow().setAttributes(lp);
  }

  @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
  private void blur(Bitmap bkg, View view) {
    long startMs = System.currentTimeMillis();
    float radius = 20;

    bkg = small(bkg);
    Bitmap bitmap = bkg.copy(bkg.getConfig(), true);

    final RenderScript rs = RenderScript.create(this.getContext());
    final Allocation overlayAlloc = Allocation.createFromBitmap(rs, bkg, Allocation.MipmapControl.MIPMAP_NONE,
        Allocation.USAGE_SCRIPT);
    final Allocation output = Allocation.createTyped(rs, overlayAlloc.getType());
    final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
    script.setRadius(radius);
    script.setInput(overlayAlloc);
    script.forEach(output);
    output.copyTo(bitmap);

    bitmap = big(bitmap);
    view.setBackground(new BitmapDrawable(getResources(), bitmap));
    rs.destroy();
    Log.d("zhangle", "blur take away:" + (System.currentTimeMillis() - startMs) + "ms");
  }

  private static Bitmap big(Bitmap bitmap) {
    Matrix matrix = new Matrix();
    matrix.postScale(4f, 4f); //长和宽放大缩小的比例
    Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    return resizeBmp;
  }

  private static Bitmap small(Bitmap bitmap) {
    Matrix matrix = new Matrix();
    matrix.postScale(0.25f, 0.25f); //长和宽放大缩小的比例
    Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    return resizeBmp;
  }

  /**
   * 获取当前屏幕截图，不包含状态栏
   *
   * @param activity
   * @return
   */
  public static Bitmap snapShotWithoutStatusBar(Activity activity)
  {
    View view = activity.getWindow().getDecorView();
    view.setDrawingCacheEnabled(true);
    view.buildDrawingCache();
    Bitmap bmp = view.getDrawingCache();
    Rect frame = new Rect();
    activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
    int statusBarHeight = frame.top;

    int width = CommonUtils.getScreenWidth();
    int height = CommonUtils.getScreenHeight();
    Bitmap bp = null;
    bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
        - statusBarHeight);
    view.destroyDrawingCache();
    return bp;
  }

  private PopupMenu popupMenu;

  private void showPopMenu() {
    if (popupMenu == null) {
      initPopMenu();
    }
    popupMenu.show();
  }

  private void initPopMenu() {
    if (popupMenu != null) {
      return;
    }
    popupMenu = new PopupMenu(getActivity(), btnPopMenu);
    popupMenu.getMenuInflater()
        .inflate(R.menu.pop_menu, popupMenu.getMenu());
    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
      @Override
      public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
          case R.id.huibo:
            popupMenu.dismiss();
            break;
          default:
            break;
        }
        return true;
      }
    });
  }

  private void updateBrightness() {
    int brightness = CommonUtils.NON_INT_DATA;
    try {
      brightness = CommonUtils.getCurrentLight(getActivity());
    } catch (Settings.SettingNotFoundException e) {
      e.printStackTrace();
    }
    CommonUtils.changeAppBrightness(getActivity(), brightness);
  }

  private void initData() {
    try {
      setSysBrightness();
      setUserBrightness();
    } catch (Settings.SettingNotFoundException e) {
      e.printStackTrace();
    }
  }

  private void setUserBrightness() throws Settings.SettingNotFoundException {
    int userBright = CommonUtils.getCurrentLight(getActivity());
    boolean userMode = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(CommonUtils.USER_BRIGHTNESS_MODE, true);
    String userModeStr = userMode ? getString(R.string.follow_system_brightness) : getString(R.string.user_brightness_manual);
    userBrightness.setText(String.format(getString(R.string.brightness), userModeStr, userBright));

    brightCb.setChecked(userMode);
    if (userBright != CommonUtils.NON_INT_DATA) {
      brightSeek.setProgress(userBright);
    }

  }

  private void setSysBrightness() throws Settings.SettingNotFoundException {
    int sysBright = Settings.System.getInt(this.getContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
    int sysBrightMode = Settings.System.getInt(getContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE);
    String sysModeStr = getString(R.string.system_mode_unkown);
    switch (sysBrightMode) {
      case Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC:
        sysModeStr = getString(R.string.system_auto_brightness);
        break;
      case Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL:
        sysModeStr = getString(R.string.system_manual_brightness);
        break;
      default:
        break;
    }
    sysBrightness.setText(String.format(getString(R.string.brightness), sysModeStr, sysBright));
  }


  private static class BottomSheetAdapter extends RecyclerView.Adapter<BottomSheetAdapter.Holder> {

    private OnItemClickListener mItemClickListener;

    private int[] textRes = {
        R.string.huibo,
        R.string.dianduidian
    };


    public void setOnItemClickListener(OnItemClickListener li) {
      mItemClickListener = li;
    }

    @Override
    public BottomSheetAdapter.Holder onCreateViewHolder(ViewGroup parent, int viewType) {
      View item = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_icon_item, parent, false);
      return new Holder(item);
    }

    @Override
    public void onBindViewHolder(final BottomSheetAdapter.Holder holder, int position) {
      if (position == 0) {
        holder.tv.setText(R.string.huibo);
      } else if (position == 1) {
        holder.tv.setText(R.string.dianduidian);
      }
      holder.icon.setImageResource(R.drawable.ic_menu_info);
      if (mItemClickListener != null) {
        holder.itemView.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            mItemClickListener.onItemClick(holder.getLayoutPosition(),
                holder.tv.getText().toString());
          }
        });
      }
    }

    @Override
    public int getItemCount() {
      return 2;
    }

    class Holder extends RecyclerView.ViewHolder {
      TextView tv;
      ImageView icon;

      public Holder(View itemView) {
        super(itemView);
        tv = (TextView) itemView.findViewById(R.id.text);
        icon = (ImageView) itemView.findViewById(R.id.icon);
      }
    }

    interface OnItemClickListener {
      void onItemClick(int position, String text);
    }
  }
}
